#include "prospeckz_radio.h"
#include "prospeckz.h"
#include "MAC.h"


#define DSP_GAME 'G'

#include "discovery.h"
#include "StopAndWait.h"

void (*MAC_ReceivedPacket)(void* data, unsigned int datalength);

void MAC_SetHandler(void (*X)(void*, unsigned int))
{
	MAC_ReceivedPacket = X;
}

void (*MAC_ReceivedBroadcast)(struct xlowpan_addr64* from, void* data, unsigned char, unsigned int datalength);

void MAC_SetBCastHandler(void (*X)(struct xlowpan_addr64* from, void*, unsigned char, unsigned int))
{
	MAC_ReceivedBroadcast = X;
}

unsigned char MAC_Buffer[MAC_MAX_PAYLOAD];
int MAC_CheckRadio(void)
{
	if (FIFOP_Data_ADDR & FIFOP_MASK) {
		
		struct xlowpan_addr64 src;
		unsigned int length = 0;
		int i = 0;

		receiveStatus_t result = Radio_receive(MAC_Buffer, MAC_MAX_PAYLOAD);
				
		if(result.radioStatus == RADIO_SUCCESS)
		{
			enum xlowpan_addr_type addr;
			unsigned char hops;
			length = result.length;
			
			MAC_ReceivedPacket(MAC_Buffer, length);
			length = xlowpan_recv5(&src, &addr,&hops, MAC_Buffer, length);
			
			if(addr == XLOWPAN_ADDR_TYPE_BCAST)
				MAC_ReceivedBroadcast(&src, MAC_Buffer, hops, length);
			else
				MAC_Decode(&src, MAC_Buffer, hops, length);
			
			return 1;
		}
	}

	return 0;
}

void MAC_Decode(struct xlowpan_addr64* from, unsigned char* data, unsigned char hops, unsigned char maxlength)
{
	switch(*data)
	{
		case DSP_RELIABLE:
			Reliable_ReceivePacket(from, data+1, hops, maxlength-1);
			break;
		case DSP_DISCOVERY:
			discovery_decodepacket(from, data, hops, maxlength);
			break;
		case DSP_GAME:
			//todo
			break;
		default:
			//do nothing
			break;
	}
}

void MAC_Transmit( void* data,unsigned int maxlength)
{	
	Radio_transmit(data, maxlength);
}
